package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1.bxscn;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateUtils;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.IDTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNShopOrder;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyBattery;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyBatteryType;
import com.gzhryc.shared_device.bxscn.code.dao.enums.PortableEnergyBatteryEnum;
import com.gzhryc.shared_device.bxscn.code.outside.znst.OpenOrCloseRequest;
import com.gzhryc.shared_device.bxscn.code.outside.znst.OpenOrCloseResponse;
import com.gzhryc.shared_device.bxscn.code.outside.znst.OperateLightResponse;
import com.gzhryc.shared_device.bxscn.code.outside.znst.ZhongNengSiTuoAPIService;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNShopOrderService;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyBatteryService;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyBatteryTypeService;
import com.gzhryc.shared_device.bxscn.code.services.dto.PortableEnergyBatterySearch;
import com.gzhryc.shared_device.bxscn.code.services.dto.PortableEnergyBatteryTypeSearch;
import com.gzhryc.shared_device.oem.code.device.BXSCNCacheManager;
import com.gzhryc.shared_device.oem.code.device.dao.models.AgentRelationBXSCNBattery;
import com.gzhryc.shared_device.oem.code.device.services.AgentRelationBXSCNBatteryService;
import com.gzhryc.shared_device.oem.code.device.services.dto.AgentRelationBXSCNBatterySearch;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceProfitUser;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.bxscn.BXSCNBatteryDeployPlaceRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.bxscn.BXSCNBatteryInfoRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.bxscn.BXSCNBatteryInfoResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.bxscn.BXSCNBatteryListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.bxscn.BXSCNBatteryListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.bxscn.BXSCNBatteryOperateRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.bxscn.BXSCNBatterySaveRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.bxscn.BXSCNBatteryTypeListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.callback.OutsideZNSKResultRequest;

public class PortableEnergyBatteryController {

    static Logger log = Logger.getLogger(PortableEnergyBatteryController.class);

    @Route(value = "/agent/api/v1/bxscn/battery/list.data")
    public BXSCNBatteryListResponse list(HttpServletRequest request) {
        BXSCNBatteryListResponse apiResp = new BXSCNBatteryListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        BXSCNBatteryListRequest apiReq = WebUtils.getJsonRequest(request, BXSCNBatteryListRequest.class);
        if (apiReq != null) {
        	 Integer pageNo = apiReq.getBody().getPageNo() == null ? 1 : apiReq.getBody().getPageNo();
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
            	 if(apiReq.getBody().getState() != null && apiReq.getBody().getState() == 0){
                     apiReq.getBody().setState(null);
                 }
            	 
            	if(ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                    PortableEnergyBatterySearch search = new PortableEnergyBatterySearch();
                    search.setUserId( loginUser.getId());
                    search.setState(apiReq.getBody().getState());
                    search.setDeviceSn(apiReq.getBody().getTrim());

                    List<PortableEnergyBattery> portableEnergyBatteryList = PortableEnergyBatteryService.self().findBySearch(search,pageNo,WebConstants.PAGE_LIMIT);
                    if(portableEnergyBatteryList != null && portableEnergyBatteryList.size() > 0){
                        apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                        apiResp.getBody().setItems(new ArrayList<>());

                        for (PortableEnergyBattery portableEnergyBattery : portableEnergyBatteryList) {
                            BXSCNBatteryListResponse.DeviceItem item = ClassTools.copy(new BXSCNBatteryListResponse.DeviceItem(), portableEnergyBattery);
                            item.setLeaseTypeName(portableEnergyBattery.getLeaseTypeName());
                            item.setPlaceAreaName(portableEnergyBattery.getAreaName());
                            item.setStateName(portableEnergyBattery.getStateName());
                            apiResp.getBody().getItems().add(item);
                        }
                    }
            	}else {
            		if(loginUser.getParentId() != null) {
	            		//先获取关联的网点，然后查询网点中的设备
	            		AgentRelationBXSCNBatterySearch search = new AgentRelationBXSCNBatterySearch();
	            		search.setState(apiReq.getBody().getState());
	                    search.setDeviceSn(apiReq.getBody().getTrim());
	                    search.setLeaseType(PortableEnergyBatteryEnum.LeaseType.ShopService.index());
	            		search.setPlaceProfitUser(new PlaceProfitUser());
	            		search.getPlaceProfitUser().setUserId(loginUser.getId());
	            		search.getPlaceProfitUser().setPlaceUserId(loginUser.getParentId());
	            		
	            		List<AgentRelationBXSCNBattery> batteryList = AgentRelationBXSCNBatteryService.self()
	            				.findJoinBySearch(search, pageNo, WebConstants.PAGE_LIMIT);
	            		
	            		if(batteryList != null && batteryList.size() > 0) {
	            			apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
	                        apiResp.getBody().setItems(new ArrayList<>());
	                        
	                        for (AgentRelationBXSCNBattery portableEnergyBattery : batteryList) {
	                            BXSCNBatteryListResponse.DeviceItem item = ClassTools.copy(new BXSCNBatteryListResponse.DeviceItem(), portableEnergyBattery);
	                            item.setLeaseTypeName(portableEnergyBattery.getLeaseTypeName());
	                            item.setPlaceAreaName(portableEnergyBattery.getAreaName());
	                            item.setStateName(portableEnergyBattery.getStateName());
	                            apiResp.getBody().getItems().add(item);
	                        }
	            		}
            		}
            	}
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/bxscn/battery/info.data")
    public BXSCNBatteryInfoResponse info(HttpServletRequest request) {
        BXSCNBatteryInfoResponse apiResp = new BXSCNBatteryInfoResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        BXSCNBatteryInfoRequest apiReq = WebUtils.getJsonRequest(request, BXSCNBatteryInfoRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                Long userId = loginUser.getId();
                if(!ERoleType.Agent.index().equals(loginUser.getRoleType())){
                    userId = loginUser.getParentId();
                }

                PortableEnergyBattery portableEnergyBattery = PortableEnergyBatteryService.self().getByDeviceSn(apiReq.getBody().getDeviceSn());
                if(portableEnergyBattery != null && portableEnergyBattery.getUserId().equals(userId)){
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                    ClassTools.copy(apiResp.getBody(),portableEnergyBattery);

                    apiResp.getBody().setLeaseTypeName(portableEnergyBattery.getLeaseTypeName());
                    apiResp.getBody().setPlaceAreaName(portableEnergyBattery.getAreaName());
                    apiResp.getBody().setStateName(portableEnergyBattery.getStateName());
                }else{
                    apiResp.setCode(ClientAPICodeConstants.NOT_POWER, "无权限查看");
                    return apiResp;
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/bxscn/battery/place/undeploy.do")
    public DefaultAPIResponse undeploy(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "移除失败");
        BXSCNBatteryDeployPlaceRequest apiReq = WebUtils.getJsonRequest(request, BXSCNBatteryDeployPlaceRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn())) {
            try {
                LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
                if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                    //去掉设备序列号中的空格和横线
                    String deviceSn = apiReq.getBody().getDeviceSn().replace(" ","");
                    deviceSn = deviceSn.replace("-","");

                    PortableEnergyBattery portableEnergyBattery = PortableEnergyBatteryService.self().getByDeviceSn(deviceSn);
                    if (portableEnergyBattery != null && portableEnergyBattery.getUserId().equals(loginUser.getId())) {
                        if (PortableEnergyBatteryService.self().undeploy(portableEnergyBattery)) {
                            apiResp.setCode(DtoConstants.SUCCESS, null);
                        }
                    } else {
                        apiResp.setMsg("电池不存在或无权限");
                    }
                }else{
                    apiResp.setMsg("无权限");
                }
            } catch (LogicException e) {
                apiResp.setMsg(e.getMessage());
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/bxscn/battery/operate.do")
    public DefaultAPIResponse operate(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "操作失败");
        BXSCNBatteryOperateRequest apiReq = WebUtils.getJsonRequest(request, BXSCNBatteryOperateRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                Long userId = loginUser.getId();
                if (!ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                    userId = loginUser.getParentId();
                }
                //去掉设备序列号中的空格和横行
                String deviceSn = apiReq.getBody().getDeviceSn().replace(" ", "");
                deviceSn = deviceSn.replace("-","");

                PortableEnergyBattery portableEnergyBattery = PortableEnergyBatteryService.self().getByDeviceSn(deviceSn);
                if (portableEnergyBattery == null || !portableEnergyBattery.getUserId().equals(userId)) {
                    apiResp.setMsg("电池不存在或无权限");
                    return apiResp;
                }

                Date createDate = new Date();
                if (StringTools.isNotBlank(apiReq.getBody().getCreateDate())) {
                    try {
                        createDate = DateUtils.parseDate(apiReq.getBody().getCreateDate(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd");
                    } catch (ParseException e) {
                        log.error(e.getMessage(), e);
                    }
                }

                if(apiReq.getBody().getHours() != null){
                    try {
                        String token = ZhongNengSiTuoAPIService.self().getToken();
                        if (StringTools.isNotBlank(token)) {
                            OpenOrCloseRequest openOrCloseRequest = new OpenOrCloseRequest();
                            Integer type = apiReq.getBody().getType() == null ? 1 : apiReq.getBody().getType();
                            if (type == 1) {
                                openOrCloseRequest.setHour(apiReq.getBody().getHours());
                            } else {
                                openOrCloseRequest.setHour(0);
                            }
                            String tradeNo = apiReq.getBody().getTradeNo();
                            if(StringTools.isBlank(tradeNo)){
                                tradeNo = IDTools.getUUID();
                            }

                            openOrCloseRequest.setTradeNo(tradeNo);
                            openOrCloseRequest.setDeviceSn(deviceSn);
                            openOrCloseRequest.setToken(token);

                            OpenOrCloseResponse openAndCloseResponse = ZhongNengSiTuoAPIService.self().sendOpenOrClose(openOrCloseRequest);
                            if (openAndCloseResponse != null) {
                                if (200 == openAndCloseResponse.getCode()) {
                                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                                    apiResp.setBody(tradeNo);
                                } else if (StringTools.isNotBlank(openAndCloseResponse.getMsg())) {
                                    apiResp.setMsg(openAndCloseResponse.getMsg());
                                } else {
                                    apiResp.setMsg("返回结果解析失败");
                                }
                            } else {
                                apiResp.setMsg("开锁无响应");
                            }
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }else {
                    BXSCNShopOrder bxscnShopOrder = BXSCNShopOrderService.self(createDate).getByTradeNo(apiReq.getBody().getTradeNo());
                    if (bxscnShopOrder != null) {
                        try {
                            String token = ZhongNengSiTuoAPIService.self().getToken();
                            if (StringTools.isNotBlank(token)) {
                                OpenOrCloseRequest openOrCloseRequest = new OpenOrCloseRequest();
                                Integer type = apiReq.getBody().getType() == null ? 1 : apiReq.getBody().getType();
                                if (type == 1) {
                                    Integer hour = bxscnShopOrder.getLeaseDay() * 24 + 24;      //默认多一天
                                    openOrCloseRequest.setHour(hour);
                                } else {
                                    openOrCloseRequest.setHour(0);
                                }
                                openOrCloseRequest.setTradeNo(bxscnShopOrder.getTradeNo());
                                openOrCloseRequest.setDeviceSn(deviceSn);
                                openOrCloseRequest.setToken(token);

                                OpenOrCloseResponse openAndCloseResponse = ZhongNengSiTuoAPIService.self().sendOpenOrClose(openOrCloseRequest);
                                if (openAndCloseResponse != null) {
                                    if (200 == openAndCloseResponse.getCode()) {
                                        apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                                        apiResp.setBody(bxscnShopOrder.getTradeNo());
                                    } else if (StringTools.isNotBlank(openAndCloseResponse.getMsg())) {
                                        apiResp.setMsg(openAndCloseResponse.getMsg());
                                    } else {
                                        apiResp.setMsg("返回结果解析失败");
                                    }
                                } else {
                                    apiResp.setMsg("开锁无响应");
                                }
                            }
                        } catch (LogicException e) {
                            apiResp.setMsg(e.getMessage());
                        }
                    }
                }
            }
        }
        return apiResp;
    }
    
    @Route(value = "/agent/api/v1/bxscn/battery/operate/result.do")
    public DefaultAPIResponse operateResult(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.NULL_DATA, "无结果");
        BXSCNBatteryOperateRequest apiReq = WebUtils.getJsonRequest(request, BXSCNBatteryOperateRequest.class);
        log.info("获取电池开启结果：{{0:json}}",apiReq);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn()) && StringTools.isNotBlank(apiReq.getBody().getTradeNo())) {
            //去掉设备序列号中的空格和横行
            String deviceSn = apiReq.getBody().getDeviceSn().replace(" ", "");
            deviceSn = deviceSn.replace("-","");

            OutsideZNSKResultRequest outsideZNSKResultRequest = BXSCNCacheManager.self().getCommandResult(deviceSn
                    ,apiReq.getBody().getTradeNo(),OutsideZNSKResultRequest.class);
            if(outsideZNSKResultRequest != null){
                apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/bxscn/battery/light/operate.do")
    public DefaultAPIResponse lightOperate(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "操作失败");
        BXSCNBatteryOperateRequest apiReq = WebUtils.getJsonRequest(request, BXSCNBatteryOperateRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                Long userId = loginUser.getId();
                if (!ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                    userId = loginUser.getParentId();
                }
                //去掉设备序列号中的空格和横行
                String deviceSn = apiReq.getBody().getDeviceSn().replace(" ", "");
                deviceSn = deviceSn.replace("-","");

                PortableEnergyBattery portableEnergyBattery = PortableEnergyBatteryService.self().getByDeviceSn(deviceSn);
                if (portableEnergyBattery == null || !portableEnergyBattery.getUserId().equals(userId)) {
                    apiResp.setMsg("电池不存在或无权限");
                    return apiResp;
                }
                
                try {
                    String token = ZhongNengSiTuoAPIService.self().getToken();
                    if (StringTools.isNotBlank(token)) {
                    	OperateLightResponse operateLightResp = ZhongNengSiTuoAPIService.self().sendOperateLignt(token,portableEnergyBattery.getDeviceSn()
                        		,apiReq.getBody().getType());
                        if (operateLightResp != null) {
                            if (200 == operateLightResp.getCode()) {
                                apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                            } else if (StringTools.isNotBlank(operateLightResp.getMsg())) {
                                apiResp.setMsg(operateLightResp.getMsg());
                            } else {
                                apiResp.setMsg("返回结果解析失败");
                            }
                        } else {
                            apiResp.setMsg("亮灯无响应");
                        }
                    }
                } catch (LogicException e) {
                    apiResp.setMsg(e.getMessage());
                }
            }
        }
        return apiResp;
    }
    
    @Route(value = "/agent/api/v1/bxscn/battery/type/list.data")
    public BXSCNBatteryTypeListResponse typeList(HttpServletRequest request){
        BXSCNBatteryTypeListResponse apiResp = new BXSCNBatteryTypeListResponse(ClientAPICodeConstants.NULL_DATA,"暂无数据");
        PortableEnergyBatteryTypeSearch search = new PortableEnergyBatteryTypeSearch();
        List<PortableEnergyBatteryType> portableEnergyBatteryTypeList = PortableEnergyBatteryTypeService.self().findBySearch(search,1,WebConstants.PAGE_LIMIT);
        if(portableEnergyBatteryTypeList != null && portableEnergyBatteryTypeList.size() > 0){
            apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
            apiResp.getBody().setItems(new ArrayList<>());

            String resDomain = PropertyTools.get().getString("resDomain");
            for(PortableEnergyBatteryType batteryType : portableEnergyBatteryTypeList){
                BXSCNBatteryTypeListResponse.Item item = new BXSCNBatteryTypeListResponse.Item();
                item.setId(batteryType.getId());
                item.setName(batteryType.getName());
                item.setThumbnailImg(WebUtils.setHttpDomain(resDomain,batteryType.getThumbnailImg()));
                apiResp.getBody().getItems().add(item);
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/bxscn/battery/save.do")
    public DefaultAPIResponse doSave(HttpServletRequest request){
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "保存成功");
        BXSCNBatterySaveRequest apiReq = WebUtils.getJsonRequest(request, BXSCNBatterySaveRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn()) && apiReq.getBody().getLeaseType() != null
                && StringTools.isNotBlank(apiReq.getBody().getBatteryType())) {
            try {
                LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
                if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                    //去掉设备序列号中的空格和横行
                    String deviceSn = apiReq.getBody().getDeviceSn().replace(" ","");
                    deviceSn = deviceSn.replace("-","");

                    PortableEnergyBattery portableEnergyBattery = PortableEnergyBatteryService.self().getByDeviceSn(deviceSn);
                    if(portableEnergyBattery == null){
                        PortableEnergyBatteryType batteryType = PortableEnergyBatteryTypeService.self().getById(apiReq.getBody().getBatteryType());
                        if(batteryType == null){
                            apiResp.setMsg("电池类型不存在");
                            return apiResp;
                        }

                        portableEnergyBattery = new PortableEnergyBattery();
                        portableEnergyBattery.setDeviceSn(deviceSn);
                        portableEnergyBattery.setType(batteryType.getId());
                        portableEnergyBattery.setTypeName(batteryType.getName());
                        portableEnergyBattery.setBatteryPower(batteryType.getBatteryPower());
                        portableEnergyBattery.setVersionNumber("1.0.0");
                        portableEnergyBattery.setLeaseType(apiReq.getBody().getLeaseType());
                        portableEnergyBattery.setUserId(loginUser.getId());
                        portableEnergyBattery.setBelongDate(new Date());

                        if(PortableEnergyBatteryService.self().add(portableEnergyBattery)){
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                        }
                    }else{
                        apiResp.setMsg("电池已存在");
                    }
                }else{
                    apiResp.setMsg("无权限");
                }
            } catch (LogicException e) {
                apiResp.setMsg(e.getMessage());
            }
        }
        return apiResp;
    }

}

